// 文件: EnemyMovement.ts (带死亡和掉落逻辑的最终版)
import { _decorator, Component, Node, Vec3, tween, Prefab, instantiate, Animation, find, v3, UITransform } from 'cc';
import { GameManager } from './GameManager';
import { UserData } from './UserData';
import { GameView } from './game/gameView/GameView';

const { ccclass, property } = _decorator;

@ccclass('EnemyMovement')
export class EnemyMovement extends Component {

    @property({ type: GameManager, tooltip: "游戏主管理器" })
    public gameManager: GameManager = null;

    @property({ tooltip: "敌人的移动速度" })
    public speed: number = 100;

    @property({ tooltip: "敌人的初始生命值" })
    public health: number = 100;

    // 【新增】元宝预制体，需要在编辑器里拖拽
    @property({ type: Prefab, tooltip: "敌人死亡后掉落的元宝预制体" })
    public coinPrefab: Prefab = null;

    private path: Vec3[] = [];
    private currentPathIndex: number = 0;
    
    private isDead: boolean = false; // 添加一个死亡标记，防止重复处理死亡逻辑
    public get IsDead(): boolean { return this.isDead; }

    private animationComponent: Animation = null; // 动画组件的引用

    onLoad() {
        this.animationComponent = this.getComponent(Animation);
    }

    public setPath(newPath: Vec3[]) {
        if (this.isDead) return; // 如果已经死了，就不再移动
        if (!newPath || newPath.length === 0) {
            this.path = [];
            this.currentPathIndex = 0;
            tween(this.node).stop();
            return;
        }
        this.path = newPath;
        this.currentPathIndex = 0;
        tween(this.node).stop();
        this.moveToNextPoint();
    }

    private moveToNextPoint() {
        if (this.isDead) return;
        if (this.currentPathIndex >= this.path.length) {
            // 敌人走到了终点
            if (this.gameManager) {
                this.gameManager.takeDamage(1); // 对基地造成1点伤害
            }
            this.node.destroy();
            return;
        }
        const targetPos = this.path[this.currentPathIndex];
        const distance = Vec3.distance(this.node.worldPosition, targetPos);
        if (distance < 0.1) {
            this.currentPathIndex++;
            this.moveToNextPoint();
            return;
        }
        const duration = distance / this.speed;
        tween(this.node)
            .to(duration, { worldPosition: targetPos })
            .call(() => {
                this.currentPathIndex++;
                this.moveToNextPoint();
            })
            .start();
    }

    /**
     * 敌人受到伤害
     * @param amount 伤害数值
     */
    public takeDamage(amount: number) {
        if (this.isDead) return; // 如果已经死了，就不再承受伤害

        this.health -= amount;
        console.log(`敌人 ${ this.node.name } 受到 ${ amount } 点伤害，剩余生命: ${ this.health }`);

        if (this.health <= 0) {
            this.die();
        }
    }

    /**
     * 敌人死亡逻辑
     */
    private die() {
        this.isDead = true;
        this.health = 0;

        // 停止所有移动
        tween(this.node).stop();

        // 从 GameManager 的敌人列表中移除自己
        if (this.gameManager) {
            this.gameManager.onEnemyDefeated(this);
        }

        // 播放死亡动画
        if (this.animationComponent && this.animationComponent.clips.some(clip => clip.name === 'death')) {
            console.log("播放死亡动画");
            this.animationComponent.play('death');
            // 监听动画播放完成事件，完成后再执行后续操作
            this.animationComponent.once(Animation.EventType.FINISHED, this.onDeathAnimationFinished, this);
        } else {
            // 如果没有死亡动画，直接执行死亡后的操作
            this.onDeathAnimationFinished();
        }
    }

    /**
     * 死亡动画播放完毕后执行
     */
    private onDeathAnimationFinished() {
        // 掉落元宝
        this.dropCoin();

        // 销毁敌人节点
        this.node.destroy();
    }

    /**
     * 掉落元宝逻辑
     */
    private dropCoin() {
        if (!this.coinPrefab) {
            console.warn("敌人没有设置元宝预制体 (Coin Prefab)，无法掉落。");
            return;
        }

        UserData.addCoin(1);

        const coin = instantiate(this.coinPrefab);
        // 确保元宝被添加到 Canvas 或其他顶层节点下
        GameView.Instance.node.addChild(coin);
        // 设置元宝的初始位置为敌人死亡的位置
        coin.setWorldPosition(this.node.worldPosition);

        // 【可选】在这里可以给元宝添加一个飞向UI的动画
        tween(coin)
            .to(0.3, { position: v3(0, -GameView.Instance.node.getComponent(UITransform).height / 2), scale: new Vec3(0.5, 0.5, 0.5) }, { easing: 'sineIn' })
            .call(() => {
                coin.destroy();
            })
            .start();
    }
}
